package com.common.utils;

import com.common.ErrorCodeEnum;
import com.common.exception.BusinessException;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * @Author: zql
 * @Description: 不同对象之间复制（浅拷贝）
 * @Data: 11:31 2021/7/11
 */
public class EntityConversionUtil {

    public static <T,S> List<T> copyList(List<S> sourceList, Class<T> classObj) {
        List<T> target = new ArrayList<>();
        if ((!Objects.isNull(sourceList))) {
            sourceList.forEach(item -> {
                try {
                    T data = classObj.newInstance();
                    BeanUtils.copyProperties(item, data);
                    target.add(data);
                } catch (InstantiationException | IllegalAccessException e) {
                    e.printStackTrace();
                    throw new BusinessException(ErrorCodeEnum.COPY_LIST_FAILED);
                }
            });
        }
        return target;
    }

    public static <T,S> List<T> copyList(Set<S> sourceList, Class<T> classObj) {
        List<T> target = new ArrayList<>();
        if ((!Objects.isNull(sourceList))) {
            sourceList.forEach(item -> {
                try {
                    T data = classObj.newInstance();
                    BeanUtils.copyProperties(item, data);
                    target.add(data);
                } catch (InstantiationException | IllegalAccessException e) {
                    e.printStackTrace();
                    throw new BusinessException(ErrorCodeEnum.COPY_LIST_FAILED);
                }
            });
        }
        return target;
    }

    public static <T,S> T copy(S source,Class<T> classObj){
        try {
            T t=classObj.newInstance();
            BeanUtils.copyProperties(source,t);
            return t;
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCodeEnum.COPY_FAILED);
        }
    }
}
